package cn.huixh.blindbox.service.impl;

import cn.huixh.blindbox.common.Common;
import cn.huixh.blindbox.common.ReturnCode;
import cn.huixh.blindbox.exception.impl.BizException;
import cn.huixh.blindbox.mapper.AccountMapper;
import cn.huixh.blindbox.pojo.po.Account;
import cn.huixh.blindbox.service.IMailService;
import cn.huixh.blindbox.service.LoginService;
import cn.huixh.blindbox.utils.JwtUtil;
import cn.huixh.blindbox.utils.RedisUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;
import java.util.concurrent.Future;

/**
 * @author huixh
 * @version 1.0
 * @date 2022/5/5 10:51
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginServiceImpl extends ServiceImpl< AccountMapper, Account > implements LoginService {

    final IMailService mailService;

    final RedisUtil redisUtil;

    final JwtUtil jwtUtil;

    /**
     * 获取登录验证码验证码时间为五分钟
     *
     * @param email 邮箱
     */
    @Override
    public void getLoginCode(String email) {

        Optional< Account > optional = Optional.ofNullable(
                this.getOne(Wrappers.< Account >lambdaQuery().eq(Account::getEmail, email), false));
        optional.ifPresentOrElse(
                account -> {
                    account.setLastDate(new Date());
                    updateById(account);
                },

                () -> save(Account.builder()
                        .email(email)
                        .createAuthor(Common.AUTHOR_USER + email)
                        .lastDate(new Date())
                        .build()));
        var s = randLoginCode();

        redisUtil.set("login_code_" + email, s, Common.MINUTE * 5L);
        log.debug("邮箱 {} 登录验证码为 {}", email, s);
        Future< String > future = mailService.simpleMail(email, "登录验证码", "您的验证码为：" + s);
        mailService.waitSendOver(future, () -> log.info("邮件发送成功 to {}", email));
    }

    @Override
    public void login(String email, String code) {
        Optional< Object > optional = Optional.ofNullable(redisUtil.get("login_code_" + email));

        optional.ifPresentOrElse(
                o -> {
                    if (!StrUtil.equals(code, o.toString(), true)) {
                        throw new BizException(ReturnCode.RC206);
                    } else {
                        redisUtil.del("login_code_" + email);
                    }
                }, () -> {
                    log.info("邮箱 {} 验证码过期！", email);
                    throw new BizException(207, "验证码过期！");
                }
        );

    }

    private String randLoginCode() {
        return RandomUtil.randomString(Common.CODE_TEMP, 6);
    }

}
